<?php
/**
 * Description: 课堂评价
 * User: devforma
 * Date: 15/12/30
 * Time: 21:00
 */

require LIB_DIR . '/LiveCourse.class.php';

class RateClass implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        global $cmsdb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id'])
            || empty($queryArgs['is_open'])) {
            return genOutput(1000);
        }

        if (empty($queryArgs['score']) || !filter_var($queryArgs['score'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        if ($queryArgs['is_open'] === 'true') { //公开课
            $room = LiveCourse::getOpenClassInfo($queryArgs['course_id']);

        } else { //直播课
            if (empty($queryArgs['class_id']))
                return genOutput(1000);

            $room = $cmsdb->getRow('SELECT `id`, `room_id`, `live_platform`, `start_time`, `end_time`, `lector_id`
            FROM `data_live_class` WHERE `id`=:cid', array(':cid' => $queryArgs['class_id']));
        }

        if (empty($room)) { //课堂信息无效
            return genOutput(1000);
        }

        //检验有效性
        $alreadyGrade = $cmsdb->getRow('SELECT `id`, `grade_score`, `lector_id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `class_id`=:cid',
            array(':uid' => $queryArgs['user_id'], ':cid' => $room->id));

        if (empty($alreadyGrade) || $alreadyGrade->grade_score != '0') { //未观看或已经评价过
            return genOutput(1001);
        }

        $comment = empty($queryArgs['comment']) ? '' : $queryArgs['comment'];
        $cmsdb->update('data_liveclass_grade',
            array(
                'grade_score' => $queryArgs['score'],
                'comment' => $comment,
                'grade_time' => date('Y-m-d H:i:s'),
                'available' => 1
            ),
            array('user_id' => $queryArgs['user_id'], 'class_id' => $room->id)
        );

        //更新课程相关字段
        $this->updateRateScore($queryArgs['score'], $queryArgs['course_id']);

        //更新教师评分
        $this->updateLectorScore($queryArgs['score'], $alreadyGrade->lector_id);

        return genOutput(1);
    }


    /**
     * 更新教师评分
     *
     * @param $newScore
     * @param $lectorId
     */
    private function updateLectorScore($newScore, $lectorId) {
        global $cmsdb;

        $scores = $cmsdb->getCol("SELECT `grade_score` FROM `data_liveclass_grade` WHERE `lector_id`=:tid AND `grde_score`!=0",
            array(':tid' => $lectorId));

        $totalCount = count($scores);
        if ($totalCount == 0)
            return;

        $totalScore = $newScore;
        foreach ($scores as $score) {
            $totalScore += $score;
        }

        $avg = round($totalScore/$totalCount, 1);
        $s = explode('.', "{$avg}");

        if (!isset($s[1])) {
            $finalScore = $s[0];
        } elseif (isset($s[1]) && ($s[1] > 0 && $s[1] <= 5)) {
            $finalScore = $s[0] + 0.5;
        } else {
            $finalScore = $s[0] + 1;
        }

        if ($finalScore > 5)
            $finalScore = 5;

        $cmsdb->update('data_live_course', array('grade_score' => $finalScore), array('id' => $lectorId));
    }

    /**
     * 更新课程评分和评价数
     *
     * @param $newScore
     * @param $courseId
     */
    private function updateRateScore($newScore, $courseId) {
        global $cmsdb;

        $classIds = getCourseClassIds($courseId);

        $idsStr = implode(',', $classIds);

        $scores = $cmsdb->getCol("SELECT `grade_score` FROM `data_liveclass_grade` WHERE `class_id` IN ({$idsStr}) AND `grade_score`!=0");

        $totalCount = count($scores);
        if ($totalCount == 0)
            return;

        $totalScore = $newScore;
        foreach ($scores as $score) {
            $totalScore += $score;
        }

        $avg = round($totalScore/$totalCount, 1);
        $s = explode('.', "{$avg}");

        if (!isset($s[1])) {
            $finalScore = $s[0];
        } elseif (isset($s[1]) && ($s[1] > 0 && $s[1] <= 5)) {
            $finalScore = $s[0] + 0.5;
        } else {
            $finalScore = $s[0] + 1;
        }

        if ($finalScore > 5)
            $finalScore = 5;

        $cmsdb->update('data_live_course', array(
            'rate_score' => $finalScore,
            'rate_num' => $totalCount
        ), array('id' => $courseId));
    }
}